#include "dswldclient.h"

CDswLdClient::CDswLdClient(LPST_ENV_T pEnv, struct bufferevent * pBev, int nHeadSize, LPST_ALARM_MSG_T pAlarmMsg, char* pHost, int nPort, bool bIsV3)
: CTcpcombase(pEnv, pBev, nHeadSize, pHost, nPort)
, m_pEnv(pEnv)
, m_nPort(nPort)
, m_bIsV3(bIsV3)
{
	memcpy(&m_nAlarmMsg, pAlarmMsg, sizeof(m_nAlarmMsg));
	memcpy(m_sHost, pHost, sizeof(m_sHost));

	LOG4CPLUS_DEBUG(log_dsw, "Create dswldclient host = " << m_sHost << ":" << m_nPort);
}

CDswLdClient::~CDswLdClient()
{
	LOG4CPLUS_DEBUG(log_dsw, "Destroy dswldclient host = " << m_sHost << ":" << m_nPort);
}

CDswLdClient* CDswLdClient::createNew(LPST_ENV_T pEnv, LPST_ALARM_MSG_T pAlarmMsg, char* pHost, bool bIsV3)
{
	struct timeval tv = {5, 0};
	struct bufferevent *pBev = bufferevent_socket_new(pEnv->pEvBase, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
	bufferevent_set_timeouts(pBev, &tv, NULL);
	int nPort;
	nPort = (bIsV3 ? LDPORT_V3 : LDPORT);
	return new CDswLdClient(pEnv, pBev, 0, pAlarmMsg, pHost, nPort, bIsV3);
}

void CDswLdClient::OnConnect(struct bufferevent * bev, short events)
{
	void* pAreCfg;
	m_pEnv->pOnNotifyFunc(PMSG_GET_ARECFG, pAreCfg);

	CMarkup xml;
	xml.SetDoc("");
	xml.AddElem("LD_DATA");
	if (m_bIsV3){
		xml.AddAttrib("ZONEID", ((LPST_ARE_PARAM)pAreCfg)->pare[m_nAlarmMsg.nAreId].id);
		xml.AddAttrib("TRIGVAL", m_nAlarmMsg.nTrigVal);
		xml.AddAttrib("TRIGTM", m_nAlarmMsg.nAlarmTime);
		xml.AddAttrib("ACTION", m_nAlarmMsg.nAction);
		xml.AddAttrib("ZONETYPE", m_nAlarmMsg.nAreType);
		int nSendLen = strlen(xml.GetDoc().c_str());
		evbuffer_add(bufferevent_get_output(m_pBev), &nSendLen, sizeof(int));
		evbuffer_add(bufferevent_get_output(m_pBev), xml.GetDoc().c_str(), nSendLen);
	}
	else{
		xml.AddChildElem("RFID", ((LPST_ARE_PARAM)pAreCfg)->pare[m_nAlarmMsg.nAreId].id);
		xml.AddChildElem("AVI", (m_nAlarmMsg.nAction & EN_VIDEO) ? 1 : 0);
		xml.AddChildElem("JPG", (m_nAlarmMsg.nAction & EN_PIC) ? 1 : 0);

		evbuffer_add(bufferevent_get_output(bev), xml.GetDoc().c_str(), strlen(xml.GetDoc().c_str()));
	}
}

